package fafu.comedu.workerrepair.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import fafu.comedu.workerrepair.R;
import fafu.comedu.workerrepair.command.Dictionary;
import fafu.comedu.workerrepair.command.LocalDataStream;
import fafu.comedu.workerrepair.command.ReJsonRsp;
import fafu.comedu.workerrepair.entitys.RecordItem;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static fafu.comedu.workerrepair.command.UnitChange.dipToPx;

public class RecordItemFragment extends Fragment {
    private static int noread = 0;
    private static int running = 1;
    private static int history = 2;
    private static int refuse  = 3;
    private static int showToast = 4;
    private static int showPD = 5;
    private static int dismissPD = 6;
    private ProgressDialog pd;
    private Integer recordId;
    private TextView title;
    private TextView iden;
    private TextView phone;
    private TextView studentAddr;
    private EditText smsg;
    private LinearLayout pics;
    private TextView mmsg;
    private RecordItem item;
    private String toastMsg;
    private String pdTitle;
    private String pdMsg;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == running)
                runRender();
            else if(msg.what == refuse)
                refRender();
            else if(msg.what == history)
                hisRender();
            else if(msg.what == noread)
                noread();
            else if(msg.what == showToast)
                showToast();
            else if(msg.what == showPD)
                showPD();
            else if(msg.what == dismissPD)
                dismissPD();
        }
    };
    private  void showPD(){
        pd= ProgressDialog.show(getActivity(), pdTitle, pdMsg);
    }
    private  void showPD(String pdTitle,String pdMsg){
        pd= ProgressDialog.show(getActivity(), pdTitle, pdMsg);
    }
    private void showToast(){
        Toast toast = Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_LONG);
        toast.show();
    }
    private void dismissPD(){
        pd.dismiss();
    }
    private void noread() {
        mmsg.setVisibility(View.GONE);
        smsg.setEnabled(true);
        smsg.setSelection(smsg.getText().length());
        try {
            String info = LocalDataStream.read(getActivity().openFileInput("data"));
            if(info.split("_")[3].equals("0")){
                smsg.setEnabled(false);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        dataRender();
    }

    private void runRender() {
        mmsg.setVisibility(View.GONE);
        smsg.setEnabled(false);
        dataRender();
    }
    private void refRender() {
        mmsg.setVisibility(View.VISIBLE);
        smsg.setEnabled(false);
        smsg.setSelection(smsg.getText().length());
        dataRender();
    }
    private void hisRender() {
        mmsg.setVisibility(View.GONE);
        smsg.setEnabled(false);
        dataRender();
    }
    public Integer getRecordId() {
        return recordId;
    }

    public void setRecordId(Integer recordId) {
        this.recordId = recordId;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        item = new RecordItem();
        View view=inflater.inflate(R.layout.record_item_main,container,false);
        title = view.findViewById(R.id.record_item_title);
        iden = view.findViewById(R.id.record_item_iden);
        phone = view.findViewById(R.id.record_item_phone);
        studentAddr = view.findViewById(R.id.record_item_studentAddr);
        smsg = view.findViewById(R.id.record_item_smsg);
        pics = view.findViewById(R.id.record_item_pics);
        mmsg = view.findViewById(R.id.record_item_mmsg);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        initRecordList();
//        iden.setText(recordId.toString());
    }
    private void dataRender() {
        title.setText(item.getTitle());
        iden.setText(item.getStudentName().toString());
        phone.setText(item.getPhone());
        studentAddr.setText(item.getStudentAddr());
        smsg.setText(item.getMsg());
        List<String> urls = item.getUrl();
        pics.removeAllViews();
        for(String url:urls){
            ImageView imageView = new ImageView(getActivity());
            Glide.with(getActivity()).load(url).into(imageView);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT);
            params.weight = (int) dipToPx(getActivity(), 100f);
            params.height = (int) dipToPx(getActivity(), 100f);
            params.gravity = Gravity.LEFT;
            pics.addView(imageView,params);
        }


    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden)  return;//隐藏页面，不操作
        //重新取值获得数据
        initRecordList();
    }

    private void initRecordList(){

        /**
         * 开始从后端取值
         */
        final OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(Dictionary.url.head+"appwork/searchItem?recordid="+recordId.toString())
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        pd= ProgressDialog.show(getActivity(), "获取信息", "获取信息中…");
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                pd.dismiss();
                Toast toast = Toast.makeText(getActivity(),"数据请求异常",Toast.LENGTH_LONG);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
                JSONObject jsonObject = (JSONObject) reJsonRsp.getData();
                item.setId((Integer) jsonObject.get("id"));
                item.setStudentName((String) jsonObject.get("studentName"));
                item.setPhone((String) jsonObject.get("phone"));
                item.setMsg((String) jsonObject.get("msg"));
                item.setOperationMsg((String) jsonObject.get("opMsg"));
                item.setStudentAddr((String) jsonObject.get("studentAddr"));
                item.setUrl((List<String>) jsonObject.get("picList"));
                item.setTitle((String) jsonObject.get("title"));
                Message message = new Message();
                Integer state = (Integer) jsonObject.get("state");
                switch (state){
                    case 0: message.what =history;break;
                    case 1: message.what = noread;break;
                    case 2:
                    case 3: message.what = running;break;
                    case 4: message.what = refuse;break;
                }
                handler.sendMessage(message);
                pd.dismiss();
            }
        });
    }
}
